import 'dart:math';

import 'package:easy_refresh/easy_refresh.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:sainbainu/common/apis/content_api.dart';
import 'package:sainbainu/common/apis/group_api.dart';
import 'package:sainbainu/common/enums/resource_type.dart';
import 'package:sainbainu/common/models/request/pager_request.dart';
import 'package:sainbainu/common/models/request/resource_request.dart';
import 'package:sainbainu/common/repositories/content_repository.dart';
import 'package:sainbainu/common/repositories/group_repository.dart';
import 'package:sainbainu/common/routes/routes.dart';
import 'package:sainbainu/common/utils/loading.dart';
import 'package:sainbainu/common/values/sizes.dart';

import 'index.dart';

class GroupDetailController extends GetxController {
  GroupDetailController();

  final state = GroupDetailState();

  @override
  void onInit() {
    super.onInit();

    if (Get.arguments == null || Get.arguments['groupId'] == null) {
      handleBack();
    }

    initHeader();

    state.groupId = Get.arguments['groupId'] as int;
    state.uniqueTag = Get.arguments['uniqueTag'] as String?;
    var groupCover = Get.arguments['cover'] as String?;
    if (groupCover != null && groupCover.isNotEmpty) {
      state.groupCover = groupCover;
    }

    state.refreshController = EasyRefreshController(
      controlFinishRefresh: false,
      controlFinishLoad: true,
    );
    state.pagerRequest = PagerRequest();
    state.groupRepository = GroupRepository(GroupApi());
    state.contentRepository = ContentRepository(ContentApi());

    getGroupDetail();
    getList();
  }

  /// 在 onInit() 之后调用 1 帧。这是进入的理想场所
  @override
  void onReady() {
    super.onReady();
  }

  /// 在 [onDelete] 方法之前调用。
  @override
  void onClose() {
    super.onClose();
    state.scrollController.dispose();
    state.refreshController.dispose();
  }

  /// 初始化头部
  initHeader() {
    state.scrollController = ScrollController();
    state.scrollController.addListener(() {
      // 计算上滑头部完全折叠
      bool isCollapsed =
          state.scrollController.offset >= kGroupCoverHeight - kToolbarHeight;
      if (state.isCollapsed.value != isCollapsed) {
        state.isCollapsed.value = isCollapsed;
      }
      // 完全展开到开始渐变时的高度
      double collapsedHeight =
          kGroupCoverHeight - kToolbarHeight - kToolbarHeight;

      if (state.scrollController.offset >= collapsedHeight) {
        // 计算上滑标题透明度
        double opacity = min(
          (state.scrollController.offset - collapsedHeight) / kToolbarHeight,
          1,
        );
        if (state.titleOpacity.value != opacity) {
          state.titleOpacity.value = opacity;
        }
      } else {
        if (state.titleOpacity.value != 0.0) {
          state.titleOpacity.value = 0.0;
        }
      }
    });
  }

  /// 详情
  Future<void> getGroupDetail() async {
    var groupDetail = await state.groupRepository.detail(state.groupId!);

    state.groupDetail = groupDetail;
    state.isJoin.value = groupDetail.joinFlag == 1;
    state.showHeaderInfo = true;
    update(['groupDetail']);
  }

  /// 返回
  void handleBack() {
    Get.back();
  }

  /// 加入、推出小组
  void handleJoin() {
    if (state.isJoin.value) {
      state.groupRepository.unjoin(state.groupId!);
    } else {
      state.groupRepository.join(state.groupId!);
    }
    state.isJoin.value = !state.isJoin.value;
  }

  /// 编辑小组
  void handleEdit() {
    Get.toNamed(
      AppRoutes.groupCreateUpdate,
      arguments: {'groupId': state.groupId},
    );
  }

  /// 小组成员页
  void toMemberPage() {
    Get.toNamed(
      AppRoutes.groupMember,
      arguments: {'groupId': state.groupId},
    );
  }

  /// 用户详情页
  toUserDetailPage(int? customerId) {
    if (customerId == null) return;
    Get.toNamed(AppRoutes.userDetail, arguments: {'customerId': customerId});
  }

  /// 获取内容列表
  Future getList({bool refresh = true}) async {
    if (refresh) {
      state.pagerRequest.pageNum = 1;
    }
    var res = await state.groupRepository.groupContentList(
      state.pagerRequest,
      state.groupId!,
    );
    if (refresh) {
      state.contentList.rows = res.rows;
    } else {
      state.contentList.rows.addAll(res.rows);
    }

    state.contentList.total = res.total;
    state.hasMore =
        state.pagerRequest.pageNum * state.pagerRequest.pageSize < res.total;
    state.pagerRequest.pageNum++;
    update(['contentList']);
  }

  /// 上拉下载
  Future onRichBottom() async {
    try {
      if (state.hasMore) {
        await getList(refresh: false);
      }
      if (!state.hasMore) {
        state.refreshController.finishLoad(IndicatorResult.noMore);
      } else {
        state.refreshController.finishLoad(IndicatorResult.success);
      }
    } catch (e) {
      state.refreshController.finishLoad(IndicatorResult.fail);
    }
  }

  /// 点赞、取消点赞
  void onGiveHandle(bool isGive, int? noteId) {
    if (noteId == null) {
      return LoadingUtil.showError('点赞失败');
    }
    var resourceRequest =
        ResourceRequest(resourceType: ResourceType.content, resourceId: noteId);
    if (isGive) {
      state.contentRepository.giveAdd(resourceRequest);
    } else {
      state.contentRepository.giveCancel(resourceRequest);
    }
  }

  /// 收藏、取消收藏
  void onCollectionHandle(bool isGive, int? noteId) {
    if (noteId == null) {
      return LoadingUtil.showError('收藏失败');
    }
    var resourceRequest =
        ResourceRequest(resourceType: ResourceType.content, resourceId: noteId);
    if (isGive) {
      state.contentRepository.collectionAdd(resourceRequest);
    } else {
      state.contentRepository.collectionCancel(resourceRequest);
    }
  }
}
